package
{
	import flash.display.Graphics;
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.MouseEvent;
	import flash.text.TextField;
	import flash.text.TextFieldType;
	
	[SWF(backgroundColor="0x0")]
	public class gesture extends Sprite
	{
		private var isPress:Boolean = false;
		private var isAdd:Boolean = true;
		private var g:Graphics;
		private var posList:Vector.<Number> = new Vector.<Number>();
		private var lib:GestureLibrary = new GestureLibrary();

		private var btn:TextField;

		private var input:TextField;
		public function gesture()
		{
			super();
			
			// 支持 autoOrient
			stage.align = StageAlign.TOP_LEFT;
			stage.scaleMode = StageScaleMode.NO_SCALE;
			
			var canvas:Shape = new Shape();
			g = canvas.graphics;
			addChild(canvas);
			
			btn = new TextField();
			btn.text = "addLib";
			btn.width = 100;
			btn.height = 45;
			btn.background = true;
			btn.backgroundColor = 0x589656;
			isAdd = true;
			addChild(btn);
			btn.addEventListener(MouseEvent.CLICK,onClick);
			
			input = new TextField();
			input.type = TextFieldType.INPUT;
			input.border = true;
			input.borderColor = 0xffffff;
			input.background = true;
			input.backgroundColor = 0x589656;
			input.x = 200;
			input.width = 200;
			input.height = 45;
			addChild(input);
			btn.textColor = input.textColor = 0xffffff;
			
			stage.addEventListener(MouseEvent.MOUSE_DOWN,onTouch);
			stage.addEventListener(MouseEvent.MOUSE_UP,onTouch);
			stage.addEventListener(MouseEvent.MOUSE_MOVE,onTouch);
		}
		
		private function onClick(e:MouseEvent):void{
			isAdd = !isAdd;
			if(!isAdd){
				btn.text = "match";
			}else{
				btn.text = "addLib";
			}
		}
		
		private function onTouch(e:MouseEvent):void{
			if(mouseY<50)return;
			switch(e.type){
				case MouseEvent.MOUSE_DOWN:
					g.clear();
					posList.push(mouseX,mouseY);
					g.lineStyle(2,0xffff00);
					g.moveTo(mouseX,mouseY);
					isPress = true;
					break;
				case MouseEvent.MOUSE_MOVE:
					if(isPress){
						posList.push(mouseX,mouseY);
						g.lineTo(mouseX,mouseY);
					}
					break;
				case MouseEvent.MOUSE_UP:
					isPress = false;
					this.createGesture();
					break;
			}
		}
		
		private function createGesture():void{
			if(posList.length<3)return;
			lib.debug(posList,g);
			if(isAdd){
				if(input.text){
					lib.addGesture(input.text,posList);
					input.text = "";
				}else{
					input.text = "快点输入名字吧";
				}
			}else{
				var instance:Instance = lib.match(posList);
				if(instance){
					trace("分数：",instance.score,"名称：",instance.label);
				}else{
					trace("无匹配");
				}
			}
			posList = new Vector.<Number>();
		}
	}
}